package com.vframework.system.org.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vframework.base.controller.BaseController;
import com.vframework.common.response.R;
import com.vframework.config.annotation.admin.AdminRestController;
import com.vframework.system.org.entity.SysOrg;
import com.vframework.system.org.service.SysOrgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织机构表 前端控制器
 * </p>
 *
 * @author codeGenerator
 * @since 2020-10-20
 */
@AdminRestController
@RequestMapping("/org")
@Api(tags = "机构管理")
public class SysOrgController extends BaseController {

    @Autowired
    private SysOrgService sysOrgService;

    @GetMapping("/{page:\\d+}/{limit:\\d+}")
    @PreAuthorize("hasAuthority('sys:org:list')")
    @ApiOperation(value = "机构列表")
    public R<IPage<SysOrg>> list(@PathVariable Long page, @PathVariable Long limit) {
        Page<SysOrg> p = new Page<>(page, limit);
        return R.success(sysOrgService.page(p));
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:org:query')")
    @ApiOperation(value = "机构详情")
    public R<SysOrg> query(@PathVariable Integer id) {
        return R.success(sysOrgService.getById(id));
    }

    @PostMapping("add")
    @PreAuthorize("hasAuthority('sys:org:add')")
    @ApiOperation(value = "添加机构")
    public R<SysOrg> addOrg(@Valid @RequestBody SysOrg sysOrg, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
            List<String> errorStr = errors.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
            throw new RuntimeException(errorStr.toString());
        }
        sysOrgService.saveOrUpdate(sysOrg, new LambdaUpdateWrapper<SysOrg>().eq(SysOrg::getId, sysOrg.getId()));
        return R.success(sysOrg);
    }

    @PostMapping("update")
    @PreAuthorize("hasAuthority('sys:org:update')")
    @ApiOperation(value = "修改机构")
    public R<SysOrg> update(@Valid @RequestBody SysOrg sysOrg, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
            List<String> errorStr = errors.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
            throw new RuntimeException(errorStr.toString());
        }
        if (BeanUtil.isEmpty(sysOrg) || sysOrg.getId() == null) {
            throw new RuntimeException("未查询到机构,修改失败");
        }
        sysOrgService.updateById(sysOrg);
        return R.success(sysOrg);
    }

}
